using B.Z.BasicData.Infrastructure;
using B.Z.Inventory.API.Read.Application.Command;
using B.Z.Inventory.API.Read.DTO;
using B.Z.Inventory.Domain;
using B.Z.Inventory.ErrorCode;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.Z.Inventory.API.Read.Application.CommandHandler
{
    /// <summary>
    /// 货品库存数量占比查询命令处理器
    /// </summary>
    public class GoodsInventoryNumberCommandHandler : IRequestHandler<GoodsInventoryNumberCommand, APIResult<GoodsInventoryNumberDto>>
    {
        private readonly IBaseRepository<T_Goods> goodsRepository;
        private readonly ILogger<GoodsInventoryNumberCommandHandler> logger;

        public GoodsInventoryNumberCommandHandler(IBaseRepository<T_Goods> goodsRepository, ILogger<GoodsInventoryNumberCommandHandler> logger)
        {
            this.goodsRepository = goodsRepository;
            this.logger = logger;
        }

        public Task<APIResult<GoodsInventoryNumberDto>> Handle(GoodsInventoryNumberCommand request, CancellationToken cancellationToken)
        {
            APIResult<GoodsInventoryNumberDto> result = new APIResult<GoodsInventoryNumberDto>();
            result.Code = APIEnums.ok;

            try
            {
                // 获取所有未删除的货品数据
                var query = goodsRepository.GetAll()
                    .AsNoTracking()
                    .Where(x => !x.IsDelete);

                // 应用筛选条件
                if (request.StoreId.HasValue)
                {
                    // 这里可能需要根据实际的仓库货品关系表进行关联查询
                    // 暂时保留接口，实际实现可能需要调整
                }

                // 计算总库存
                var totalStock = query.Sum(x => x.SystemNum ?? 0);

                if (totalStock == 0)
                {
                    result.Data = new GoodsInventoryNumberDto
                    {
                        Count = 0,
                        ShowGoods = new List<GoodsDtos>()
                    };
                    return Task.FromResult(result);
                }

                // 计算每个商品的库存占比
                var goodsList = query
                    .Where(x => x.SystemNum > 0)
                    .Select(goods => new GoodsDtos
                    {
                        GoodsId = goods.Id,
                        GoodsName = goods.GoodsName,
                        Percentage = totalStock > 0 ? Math.Round((double)(goods.SystemNum ?? 0) / totalStock * 100, 2) : 0
                    })
                    .OrderByDescending(x => x.Percentage)
                    .Take(request.TopCount)
                    .ToList();

                result.Data = new GoodsInventoryNumberDto
                {
                    Count = goodsList.Count,
                    ShowGoods = goodsList
                };

                logger.LogInformation($"成功获取货品库存占比，共{goodsList.Count}条记录，总库存：{totalStock}");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取货品库存占比时发生错误");
                result.Code = APIEnums.fail;
                result.Message = "获取货品库存占比失败";
            }

            return Task.FromResult(result);
        }
    }
}